/*
 * OPIAM Suite
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */

package opiam.admin.applis.demo.actions;

import opiam.admin.applis.demo.beans.Group;
import opiam.admin.applis.demo.beans.Person;
import opiam.admin.applis.demo.forms.GroupForm;
import opiam.admin.faare.SearchResult;
import opiam.admin.faare.service.UserContext;
import opiam.admin.faare.service.services.SortService;
import opiam.admin.faare.struts.actions.SecureAction;
import opiam.admin.faare.struts.utils.SessionContext;

import org.apache.log4j.Logger;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;


/**
 * This action allows to add a selected subset of users to a group.
 */
public class GroupAddUsersAction extends SecureAction
{
    /** Logger de log4j. */
    private static Logger _logger = Logger.getLogger(GroupAddUsersAction.class);

    /**
     * Struts Action method.
     * See SecureAction
     *
     * @param mapping Struts mapping data.
     * @param actionForm Input form.
     * @param request HTTP request.
     * @param httpServletResponse HTTP response.
     *
     * @return forward to success or to error
     *
     * @throws java.io.IOException see Action.execute()
     * @throws javax.servlet.ServletException see Action.execute()
     */
    @Override
	public ActionForward secureExecute(ActionMapping mapping,
                                       ActionForm actionForm,
                                       HttpServletRequest request,
                                       HttpServletResponse httpServletResponse
                                      ) throws IOException, ServletException
    {
        SessionContext sessionContext = null;
        UserContext userContext = null;
        ActionMessages errors = new ActionMessages();
        try
		{

        // Gets the session.
        HttpSession session = request.getSession();
        // Gets the session context.
        sessionContext = SessionContext.getInstance(session);
        // Gets the user context.
        userContext = sessionContext.getUserContext();
        // Gets the form
        GroupForm gf = (GroupForm)actionForm;
       
        // Gets the request parameters
        String[] elements = request.getParameterValues("groupeltindex");
        String selection = request.getParameter("groupselection");

        if (elements == null)
        {
            return (mapping.findForward("success"));
        }
        
        // Gets the members of the group
        Group group = gf.getGroup();
        Collection members = group.getUniqueMember();
        HashMap hmembers = new HashMap();
        Iterator iter = members.iterator();
        
        while(iter.hasNext())
        {
        	Person person = (Person)iter.next();
        	hmembers.put(person.getId(), person);
        }
        
        // Gets the search results
        SearchResult result =
            (SearchResult) session.getAttribute("groupUsersSearchResult");
        List results = result.getLResults();

        if (selection.equals("all"))
        {
            // Add the search result to the temporary list
            for (int i = 0; i < results.size(); i++)
            {
            	Person person = (Person)results.get(i);
            	if (!hmembers.containsKey(person.getId()))
            	{
            		hmembers.put(person.getId(), person);
            	}
            }
        }
        else
        {
            for (int i = 0; i < elements.length; i++)
            {
                Person person = (Person) results.get(Integer.parseInt(elements[i]));
                if (!hmembers.containsKey(person.getId()))
                {
                	hmembers.put(person.getId(), person);
                }
            }
        }
        
        List lmembers = new ArrayList();
        lmembers.addAll(hmembers.values());

        // Sorts the list
        SortService.sort(lmembers, Person.class, "name", userContext);
        
        // Updates the formbean
        group.setUniqueMember(lmembers);
        gf.setGroup(group);

            return (mapping.findForward("success"));
        }
        catch (Exception se)
        {
            _logger.debug("Trace", se);
            _logger.error(se.getMessage());
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("error.service.unknown")
                      );
            saveErrors(request, errors);

            return (mapping.findForward("error"));
        }
    }
}
